谈谈 Refs
是什么
- Refs 属性提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。
- 这个特殊的属性允许你引用 render() 返回的相应的实,这样就可以确保在任何时间总是拿到正确的实例。
怎么用
创建 Refs
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
访问 Refs
const node = this.myRef.current;
何时使用 Refs
- 处理 focus、文本选择或者媒体播放
- 触发强制动画
- 集成第三方 DOM 库
如果可以通过声明式实现,就尽量避免使用 refs 。
例如,相比于在 Dialog 组件中暴露 open() 和 close() 方法,最好传递 isOpen
属性。
不要过度使用 Refs
你可能首先会想到在你的应用程序中使用 refs 来更新组件。如果是这种情况,请花一点时间,更多的关注在组件层中使用 state。在组件层中,通常较高级别的 state 更为清晰(状态提升)
import React from "react";
import "./styles.css";
const inputRef = React.createRef();
class App extends React.Component {
handleSave = () => {
console.log(inputRef.current.value);
};
render() {
return (
<div>
<TextInput ref={inputRef} />
<button onClick={this.handleSave}>保存</button>
</div>
);
}
}
const TextInput = React.forwardRef((props, ref) => (
<input type="text" placeholder="请输入表名" ref={ref} />
));
export default App;